home *** CD-ROM | disk | FTP | other *** search
- Path: bubba.NMSU.Edu!usenet
- From: ghenniga@ampere.NMSU.Edu (Gary Hennigan)
- Newsgroups: comp.lang.c
- Subject: Re: accessing structures (newbie question)
- Date: 21 Feb 1996 09:52:17 -0700
- Organization: New Mexico State University - Electromagnetics Group
- Sender: ghenniga@ampere.NMSU.Edu
- Message-ID: <rhthgwk1v0e.fsf@ampere.NMSU.Edu>
- References: <4g8gic$o6u@news1.sunbelt.net>
- Reply-To: ghenniga@NMSU.Edu
- NNTP-Posting-Host: ampere.nmsu.edu
- In-reply-to: dking@SunBelt.Net's message of 19 Feb 1996 00:34:20 GMT
- X-Newsreader: Gnus v5.1
-
- In an article dking@SunBelt.Net wrote:
- >Ok. having trouble accessing structure. here I define a pointer and
- >malloc the memory:
- >
- >struct picture *photos;
- >photos = (struct picture *)malloc(1000 * sizeof(picture));
- >
- >now I try to store data into structures...
- >
- > for (x=0;x<num_of_files;x++)
- > {
- > strncpy(photos->filename, filelist[x],12);
- > strncpy(photos->diskname, inputdisk,12);
- > strncpy(photos->indexname, inputindex,12);
- > }
- >
- >now I try to read data...
- >
- >for (x=0;x<num_of_files;x++)
- >{
- >
- > printf("%sdisk%sindex%s\n",photos->filename,
- > photos->diskname,photos->indexname);
- >}
- >
- >Obviously I'm pointing to the first of the 1000 structures the entire time.
- >Now for the 60,000 dollar question: HOW do I access the rest of the
- >structures? My tutuorial doesnt have any examples of accessing MALLOCed
- >structures. The one example on structures defines it as an array (struct
- >picture *photos[x] ) but 1000 elements is too large an array and the
- >example
-
- You probably meant:
- struct picture photos[x];
-
- Quite different from
- struct picture *photos[x];
-
- >with malloc uses floating point data accessed by using (photos[x]) which
- >doesnt work either with the strnccpy or with the -> operator.
- >
- >I'd Appreciate any assistance you might offer.
-
- Easiest way:
-
- for(x=0; x < num_of_files; x++)
- {
- strncpy((photos+x)->filename, filelist[x], 12);
- strncpy((photos+x)->diskname, inputdisk, 12);
- strncpy((photos+x)->indexname, inputindex, 12);
- }
-
- similiar for your printf()
-
- Also valid:
-
- for(x=0; x < num_of_files; x++)
- {
- strncpy(photos[x].filename, filelist[x], 12);
- strncpy(photos[x].diskname, inputdisk, 12);
- strncpy(photos[x].indexname, inputindex, 12);
- }
-
- This assumes you have allocated, or statically declared, all the
- character array members within the structure appropriately.
-
- You need to brush up on pointers and indirect/direct addressing.
-
- Gary
- (ghenniga@NMSU.Edu)
-